package by.grsu.verkhovodko.dao.impl;

import java.io.Serializable;
//import java.util.ArrayList;
//import java.util.Date;
import java.util.List;

import by.grsu.verkhovodko.entity.Train;
import by.grsu.verkhovodko.table.TrainTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class TrainDao extends AbstractDao<TrainTable, Train> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7616398199418924442L;

	public TrainDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Train newTrain) {
		// set ID
		//Long nextId = getNextId();
		newTrain.setId(getNextId());
		// get existing data
		final TrainTable trainTable = deserializeFromXml();
		// add new row
		trainTable.getRows().add(newTrain);
		// save data
		serializeToXml(trainTable);
		
	}

	@Override
	public void update(final Train entity) {
		// get existing data
		final TrainTable trainTable = deserializeFromXml();
		// find by ID
		for (final Train row : trainTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setId(entity.getId());
				row.setDestStation(entity.getDestStation());
				row.setDateOfDeparture(entity.getDateOfDeparture());
				row.setCost(entity.getCost());
				break;
			}
		}
		// save updated table
		serializeToXml(trainTable);
	}

	@Override
	public Train get(final Serializable id) {
		// get existing data
		final TrainTable trainTable = deserializeFromXml();
		// find by ID
		for (final Train row : trainTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}
	
	@Override
	public List<Train> getAll() {
		// get existing data
		final TrainTable trainTable = deserializeFromXml();
		return trainTable.getRows();
	}
	
	@Override
	public void delete(final Serializable id) {
		// get existing data
		final TrainTable trainTable = deserializeFromXml();
		// find by ID
		Train toBeDeleted = null;
		for (final Train row : trainTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		trainTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(trainTable);
	}

	/*public List<Train> getTrainsInDayToStation(Date date, String station) {
		List<Train> result = new ArrayList<Train>();
		List<Train> allTrains = getAll();
		for (Train train : allTrains) {
			if (station.equals(train.getDestStation()) &&
					train.getDateOfDeparture().getMonth() == date.getMonth() &&
					train.getDateOfDeparture().getDate() == date.getDate()) {
						result.add(train);
			}
		}
		return result;
	}
	*/
	@Override
	protected Class<TrainTable> getTableClass() {
		return TrainTable.class;
	}

}
